<template>
  <ContentWrap>
    <div class="flex justify-between text-lg font-bold mr-150">
      <div class="flex items-center flex-col">
        <div class="mb-6">账户总资金</div>
        <div>{{ overView?.totalFundsTotal || 0 }}万元</div>
      </div>
      <div class="flex items-center flex-col">
        <div class="mb-6">可用资金</div>
        <div>{{ overView?.availableFundsTotal || 0 }}万元</div>
      </div>
      <div class="flex items-center flex-col">
        <div class="mb-6">保证金</div>
        <div>{{ overView?.bondTotal || 0 }}万元</div>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="accountName">
        <el-input
          clearable
          :maxlength="50"
          v-model="queryParams.accountName"
          placeholder="请输入客户名称"
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="contactPhone">
        <el-input
          clearable
          :maxlength="11"
          v-model="queryParams.contactPhone"
          placeholder="请输入手机号"
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="账户状态" prop="state">
        <el-select clearable v-model="queryParams.state" placeholder="请选择" class="!w-200px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_CUSTOMER_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          type="datetimerange"
          class="!w-400px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['bid:financeAccount:exportexcel']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      border
      stripe
      :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
    >
      <el-table-column label="编号" align="center" width="60">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="客户名称"
        align="center"
        prop="accountName"
        min-width="250"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <span class="text-blue-500 cursor-pointer" @click="getPageType(1, row.customerId)">{{
            row.accountName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="contactPhone" min-width="150" />
      <el-table-column label="状态" align="center" prop="state" width="150">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.BID_CUSTOMER_STATE" :value="row.state" />
        </template>
      </el-table-column>
      <el-table-column label="账户总资金(元)" align="center" prop="totalFunds" width="150" />
      <el-table-column label="保证金(元)" align="center" prop="bond" width="150" />
      <el-table-column label="可用资金(元)" align="center" prop="availableFunds" width="150" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="250"
      />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            v-hasPermi="['bid:financeAccount:deduct']"
            @click="deductionFn(row.id)"
          >
            扣款
          </el-button>
          <el-dropdown @command="handleCommand($event, row)">
            <el-button link type="primary"> 更多<Icon icon="ep:d-arrow-right" /> </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-container v-hasPermi="['bid:financeAccount:onAndOff']">
                  <el-dropdown-item v-if="row.state === 0" command="close"> 关闭 </el-dropdown-item>
                  <el-dropdown-item v-if="row.state === 1" command="close"> 开启 </el-dropdown-item>
                </el-container>
                <el-container v-hasPermi="['bid:financeAccount:financeDetail']">
                  <el-dropdown-item command="transRecords"> 交易记录 </el-dropdown-item>
                </el-container>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <DeductionModel ref="deductionModel" @success="success"></DeductionModel>
</template>
<script lang="ts" setup name="accountManageAdmin">
import * as Utils from '@/utils/dict'
import { useRouter } from 'vue-router'
import download from '@/utils/download'
import * as financial from '@/api/financial'
import DeductionModel from './deductionModel.vue'
import { dateFormatter } from '@/utils/formatTime'

const total = ref(0)
const list = ref([])
const { t } = useI18n()
const loading = ref(true)
const queryFormRef = ref()
const router = useRouter()
const deductionModel = ref()
const message = useMessage()
const exportLoading = ref(false)
const emit = defineEmits(['subPage'])
const overView: Record<string, any> = ref({})
const { DICT_TYPE, getIntDictOptions } = reactive(Utils)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  accountName: undefined,
  contactPhone: undefined,
  state: undefined,
  createTime: []
})

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const getList = async () => {
  loading.value = true
  try {
    const data = await financial.financeAccountList(queryParams)
    list.value = data.list
    total.value = data.total
    overView.value = {
      totalFundsTotal: data.totalFundsTotal,
      availableFundsTotal: data.availableFundsTotal,
      bondTotal: data.bondTotal
    }
  } finally {
    loading.value = false
  }
}

const success = () => {
  handleQuery()
}

const getPageType = (index, id) => {
  emit('subPage', index, id)
}

const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await financial.financeAccountExport(queryParams)
    download.excel(data, '账户列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleCommand = (command, row) => {
  if (command === 'close') {
    ElMessageBox.confirm(`确认要${row.state === 0 ? '关闭' : '开启'}该账户？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      financeAccountOnAndOff(row)
    })
    return
  }
  if (command === 'transRecords') {
    router.push({
      path: '/bidManageAdmin/financial/transDetails',
      query: { accountName: row.accountName }
    })
  }
}

const financeAccountOnAndOff = async (row) => {
  loading.value = true
  try {
    const data = {
      id: row.id,
      state: row.state === 0 ? 1 : 0
    }
    await financial.financeAccountOnAndOff(data)
    message.success(t('common.operateSuccess'))
    getList()
  } finally {
    loading.value = false
  }
}

const deductionFn = (id: number) => {
  deductionModel.value.open(id)
}

onMounted(async () => {
  getList()
})
</script>
<style scoped>
:deep(.el-button:focus-visible) {
  outline: 0 !important;
}
</style>
